package com.turing.common.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.turing.common.util.StringUtils;
import lombok.extern.flogger.Flogger;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.stereotype.Component;

import com.turing.common.entity.Context;
import com.turing.common.entity.UserToken;
import com.turing.common.spring.SpringApplicationContext;
import com.turing.common.util.JwtUtil;
import com.turing.common.util.Log;
import com.turing.common.util.Tools;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;

/**
 * @Description 过滤器
 * @Author lcy
 * @Date 2021/5/17 14:37
 */
@WebFilter(urlPatterns = "/*", filterName = "userTokenFilter")
@Component
@AllArgsConstructor
@Slf4j
public class UserTokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        String url = ((HttpServletRequest) servletRequest).getRequestURL().toString();
        if (!url.contains("/element/getTemplateByPage") && !url.contains("/element/getTemplate") && !url.contains("/template/queryByCondition")
                && !url.contains("/process") && !url.contains("/draw/uploadFileAndCreateTask") && !url.contains("/review/getTaskElements") || url.contains("/process/createTaskRecords") ) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        UserToken userToken = UserToken.builder().build();
        if (StringUtils.isNotEmpty(token)) {
            try{
                String tokenStr = URLDecoder.decode(token, "UTF-8");
                JSONObject claims = JSONObject.parseObject(tokenStr);
                //设置线程变量
                userToken.setUserId(Tools.isEmpty(claims.get("jti")) ? null : Integer.parseInt(claims.get("jti").toString()))
                        .setUserCode(Tools.isEmpty(claims.get("userCode")) ? null : claims.get("userCode").toString())
                        .setUserName(Tools.isEmpty(claims.get("sub")) ? null : claims.get("sub").toString())
                        .setRoleId(StringUtils.isEmpty(claims.get("mainRoleId")) ? null : Integer.parseInt(claims.get("mainRoleId").toString()))
                        .setRoleName(Tools.isEmpty(claims.get("mainRoleName")) ? null : claims.get("mainRoleName").toString())
                        .setRoleUserIds(Tools.isEmpty(claims.get("roleUserIds")) ? new ArrayList<>() : (List<Integer>) claims.get("roleUserIds"))
                        .setMenuList(Tools.isEmpty(claims.get("menuList")) ? new HashSet<>() : new HashSet<>((List<Integer>) claims.get("menuList")))
                        .setTemplates(Tools.isEmpty(claims.get("templates")) ? new HashMap<>() : (Map<String,Integer>) claims.get("templates"))
                        .setElements(Tools.isEmpty(claims.get("elements")) ? new HashMap<>() : (Map<String,Set<Integer>>) claims.get("elements"))
                        .setOcrTemplates(Tools.isEmpty(claims.get("ocrTemplates")) ? new HashSet<>() : new HashSet<>((List<String>) claims.get("ocrTemplates")))
                        .setDataPrivilege(Tools.isEmpty(claims.get("dataPrivilege")) ? null : (Map<String,List<Integer>>)claims.get("dataPrivilege"));
            }catch (Exception e){
                log.error(e.getMessage());
            }

        }
        Context.setTokenContext(userToken);

        filterChain.doFilter(servletRequest, servletResponse);

    }

}
